package com.mf.basic.excel;

import cn.hutool.core.bean.BeanUtil;
import com.mf.basic.utils.UtilsDate;
import com.mf.basic.entity.vo.VoExcel;
import com.mf.basic.exceptions.MyException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UtilsExcel {

    /**
     * 通用EXCEL导出模板
     * @param itemList 列表详细
     * @param mainMap 主表对象
     * @param excelTemplatePath 模板文件全路径
     * @param exportName 导出名称
     * @param response Rsp
     */
    public static void doExcel(List<?> itemList, Map<String, Object> mainMap,
                               String excelTemplatePath, String exportName, HttpServletResponse response) throws IOException {
        if(CollectionUtils.isEmpty(itemList)){
            return;
        }
        //导出的文件名及默认路径
        String fileName = exportName + ".xlsx"; // 文件名
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
        response.setHeader("download-filename", fileName);
        ServletOutputStream out = response.getOutputStream();

        //填充模板
        ExcelWriter excelWriter = EasyExcel.write(out)
                .withTemplate(excelTemplatePath).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(itemList, fillConfig, writeSheet);
        excelWriter.fill(mainMap, writeSheet);
        //关闭流
        excelWriter.finish();
        out.flush();
        response.getOutputStream().close();
        out.close();
    }

    /**
     * 通用EXCEL导出模板
     * @param itemList 列表详细
     * @param mainMap 主表对象
     * @param excelTemplatePath 模板文件全路径
     * @param exportName 导出名称
     * @param response Rsp
     */
    public static void doExcel(List<?> itemList, Map<String, Object> mainMap,
                               String excelTemplatePath, String exportName,
                               int mergeRowIndex, int[] mergeColumnIndex,
                               HttpServletResponse response) throws IOException {
        if(CollectionUtils.isEmpty(itemList)){
            return;
        }
        //导出的文件名及默认路径
        String fileName = exportName + ".xlsx"; // 文件名
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
        response.setHeader("download-filename", fileName);
        ServletOutputStream out = response.getOutputStream();

        //填充模板
        ExcelWriter excelWriter = EasyExcel.write(out)
                .registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex,mergeColumnIndex))
                .withTemplate(excelTemplatePath).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(itemList, fillConfig, writeSheet);
        excelWriter.fill(mainMap, writeSheet);
        //关闭流
        excelWriter.finish();
        out.flush();
        response.getOutputStream().close();
        out.close();
    }

    /**
     * 通用EXCEL导出模板
     * @param itemList 列表详细
     * @param mainMap 主表对象
     * @param excelTemplatePath 模板文件全路径
     * @param exportName 导出名称
     * @param response Rsp
     */
    public static void doExcel(List<?> itemList, Map<String, Object> mainMap,
                               String excelTemplatePath, String exportName,
                               int mergeRowIndex, int startColumnIndex, int endColumnIndex,
                               HttpServletResponse response) throws IOException {
        if(CollectionUtils.isEmpty(itemList)){
            return;
        }
        //导出的文件名及默认路径
        String fileName = exportName + ".xlsx"; // 文件名
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
        response.setHeader("download-filename", fileName);
        ServletOutputStream out = response.getOutputStream();

        //填充模板
        ExcelWriter excelWriter = EasyExcel.write(out)
                .registerWriteHandler(new ExcelFillCellMergeStrategy_1(mergeRowIndex,startColumnIndex,endColumnIndex))
                .withTemplate(excelTemplatePath).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(itemList, fillConfig, writeSheet);
        excelWriter.fill(mainMap, writeSheet);
        //关闭流
        excelWriter.finish();
        out.flush();
        response.getOutputStream().close();
        out.close();
    }

    /**
     * 将列表导出到EXCEL
     */
    public static void doExcel(VoExcel voExcel, HttpServletResponse response) throws IOException {
        if(CollectionUtils.isEmpty(voExcel.getDataList())){
            throw new MyException("条件下导出内容为空, 请检查");
        }
        //生成标题栏
        List<List<String>> headList = new ArrayList<>();
        List<String> head;
        for(String s : voExcel.getColumns()){
            head = new ArrayList<>();
            head.add(s);
            headList.add(head);
        }
        //文件名
        String fileName = voExcel.getFileName() + "."+ UtilsDate.getNowTimestamp()+".xlsx";
        //生成数据
        List<List<Object>> data = new ArrayList<>();
        List<Object> rowList;
        Object tmp;
        for(Object t : voExcel.getDataList()){
            Map<String, Object> map = BeanUtil.beanToMap(t);
            rowList = new ArrayList<>();
            for(String field : voExcel.getFieldNames()){
                tmp = map.get(field);
                if(null != tmp){
                    rowList.add(tmp);
                }
            }
            data.add(rowList);
        }
        //导出的文件名及默认路径
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( voExcel.getFileName().getBytes("gb2312"), "ISO8859-1" ));
        response.setHeader("download-filename", fileName);
        ServletOutputStream out = response.getOutputStream();
        //导出
        EasyExcel.write(out)
                .head(headList)
                .sheet(voExcel.getSheetName())
                .doWrite(data);
        //关闭流
        out.flush();
        response.getOutputStream().close();
        out.close();
    }

}
